package com.zeratul.common.event.core.server.publish;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.event.base.BasePublishHandler;
import com.zeratul.common.event.base.BasePublishServer;
import com.zeratul.common.event.domain.ZtEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 默认的服务层【发布者】处理器
 */
@Slf4j
public class StandardPublishServer implements BasePublishServer {

    /**
     * 发布者执行器
     */
    @Autowired
    private BasePublishHandler publishHandler;

    /**
     * 发布事件对象
     *
     * @param ztEvent
     */
    @Override
    public <T> void sendEvent(ZtEvent<T> ztEvent) {
        //执行发布者拦截器逻辑
        ztEvent = doInterceptor(ztEvent);
        //如果返回null，则终止消息的发送
        if (ObjectUtil.isNull(ztEvent)) {
            return;
        }

        //序列化消息对象
        byte[] eventBytes = publishHandler.serialize(ztEvent);
        //调用发布者执行器发布消息
        publishHandler.doSendEvent(ztEvent, eventBytes);
    }
}
